﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.SqliteWrapper;
using ZilLion.Service.TaskPlatform.Domain.Entity;
using ZilLion.Service.TaskPlatform.Domain.Respository.Interface;

namespace ZilLion.Service.TaskPlatform.Domain.Respository.Sqlite
{
    public class SqliteTaskStateRespository : SqliteRepository<TaskStateEntity>, ITaskStateRespository
    {
        public SqliteTaskStateRespository()
        {
            Context = new TaskRunnerSqliteContext();
        }

        /// <summary>
        ///     获取当前serverid所有记录
        /// </summary>
        /// <returns></returns>
        public IEnumerable<TaskStateEntity> GetAllTaskState(string nodeid = null)
        {
            if (nodeid.IsNotNullOrEmpty())
                return
                    GetList(@"select * from task_state where nodeid=@nodeid",
                        new {nodeid}).ToList();
            return GetList(@"select * from task_state "
            ).ToList();
        }

        /// <summary>
        ///     按ID 或者log
        /// </summary>
        /// <param name="taskid"></param>
        /// <param name="nodeid"></param>
        /// <returns></returns>
        public TaskStateEntity GetTaskState(string taskid, string nodeid = null)
        {
            if (nodeid.IsNotNullOrEmpty())

                return
                    GetList(@"select * from task_state where taskid=@taskid and nodeid=@nodeid",
                        new {nodeid, taskid}).FirstOrDefault();
            return GetList(@"select * from task_state where taskid=@taskid",
                new {nodeid, taskid}).FirstOrDefault();
        }

        /// <summary>
        ///     修改
        /// </summary>
        /// <param name="logEntity"></param>
        public void SaveTaskRunState(TaskStateEntity logEntity, UnitOfWork unit = null)
        {
            if (logEntity == null) return;
            var old = GetTaskState(logEntity.Taskid, logEntity.NodeId);
            if (old != null)
            {
                old.Taskstatus = logEntity.Taskstatus;
                Modify(logEntity, unit);
            }

            else
            {
                Add(logEntity, unit);
            }

        }

        public void SaveTaskExcuteCount(TaskStateEntity logEntity, UnitOfWork unit = null)
        {
            if (logEntity == null) return;
            var old = GetTaskState(logEntity.Taskid, logEntity.NodeId);
            if (old != null)
            {
                old.TaskErrorCount = logEntity.TaskErrorCount;
                old.TaskExcutedCount = logEntity.TaskExcutedCount;
                old.Tasklastruntime = logEntity.Tasklastruntime;
                old.Tasknextruntime = logEntity.Tasknextruntime;
                Modify(old, unit);
            }
        }
        public void RemoveTaskState(TaskStateEntity logEntity, UnitOfWork unit = null)
        {
            Remove(logEntity, unit);
        }


      
    }
}